<template>
  <div class="studyed-step-wrap">
    <div class="step-content">
      <div class="pass-icon">
        <img
          v-if="!passByHandSuccess && score < 60"
          src="~assets/reverse/score-fail.png"
          alt=""
        />
        <img
          v-if="passByHandSuccess || score >= 60"
          src="~assets/reverse/score-pass.png"
          alt=""
        />
      </div>
      <div class="step-text">
        <div @click="sceneClick('title')">
          <div class="scene-title" :class="{ 'scene-hidden': titleHidden }">
            <span
              v-for="(word, i) in renderHtml"
              :key="word + i"
              :class="{ 'keys-words': keysIndex.includes(i) }"
              >{{ word }}</span
            >
          </div>
        </div>
        <p class="scene-translation" @click="sceneClick('translation')">
          {{ data.translation }}
        </p>
      </div>
      <div>
        <div @click="playHandle" v-if="score >= 60" class="scene-play">
          <img
            v-show="!playing"
            src="~assets/reverse/studyed-play.png"
            alt=""
          />
          <img
            v-show="playing"
            src="~assets/reverse/studyed-pause.png"
            alt=""
          />
          <p v-show="!playing">开始播放</p>
          <p v-show="playing">暂停播放</p>
        </div>
        <div class="scene-byhand" v-else>
          <div @click="playHandle">
            <img
              v-show="!playing"
              src="~assets/reverse/record-fail-play.png"
              alt=""
            />
            <img
              v-show="playing"
              src="~assets/reverse/record-fail-pause.png"
              alt=""
            />
            <p v-show="!playing">开始播放</p>
            <p v-show="playing">暂停播放</p>
          </div>
          <div @click="passByHand" v-show="!passByHandSuccess && score < 60">
            <img src="~assets/reverse/pass-byhand.png" alt="" />
            <p>人工通过</p>
          </div>
        </div>
      </div>
    </div>
    <div class="finish-bottom">
      <div class="voice-wrap">
        <span class="play-time">{{ seekDuration | mmssFilter }}</span>
        <a-slider
          :tipFormatter="null"
          class="voice-range"
          :value="sliderPercentage"
        ></a-slider>
        <span class="all-time">{{ audioDuration | mmssFilter }}</span>
      </div>
      <div class="next">
        <a-button
          type="primary"
          v-if="!passByHandSuccess && score < 60"
          shape="round"
          @click="studyAgain"
          >再测一次</a-button
        >
        <a-button
          class="study-next-btn"
          type="primary"
          shape="round"
          @click="studyNext"
          >学下一句</a-button
        >
      </div>
    </div>
    <Timetips></Timetips>
  </div>
</template>

<script>
import { Slider } from "ant-design-vue";
import { Howl } from "howler";
import { mapState, mapMutations } from "vuex";
import { SUCCESS_CODE } from "@/utils/const";
import { grammarSenRatioSub } from "@/services/reverse";
import { findNextTarget } from "@/utils/tools";
import Timetips from "@/components/Timetips";
export default {
  components: {
    ASlider: Slider,
    Timetips
  },
  data() {
    return {
      keysIndex: [],
      data: {},
      translate: {},
      keysWords: [],
      titleHidden: false,
      audioDuration: 0,
      seekDuration: 0,
      passByHandSuccess: false,
      againBtnShow: true,
      playing: false,
      htmlAudio: {},
    };
  },
  props: {
    renderData: {
      type: Object,
    },
    sentenceCurrent: {
      type: Object,
    },
    tabKey: {
      type: Number,
    },
    score: {
      type: Number,
    },
    recordUrl: {
      type: String,
    },
    nextList: {
      type: Object,
    }, // 录音提交后的  test
  },
  computed: {
    ...mapState({
      reverseStatus: (state) => state.reverseStatus,
      sentenceList: (state) => state.sentenceList,
    }),
    renderHtml: function() {
      return this.data.title.split(" ");
    },
    sliderPercentage: function() {
      return Math.ceil((this.seekDuration / this.audioDuration) * 100);
    },
  },
  watch: {
    renderData: {
      handler: function(val) {
        console.log(val);
        let current = val.list.find((v) => v.id === this.sentenceCurrent.id);
        this.data = current;
        this.keysWords = current.keys_words.split(" ");
        let tmp = this.data.title.replace(
          new RegExp(`(${current.keys_words.split(",").join("|")})`, "ig"),
          (w) => {
            return `##${w.split(" ").join("## ##")}##`;
          }
        );
        tmp = tmp.split(" ");
        for (let i in tmp) {
          if (/^##.+##$/.test(tmp[i])) {
            this.keysIndex.push(Number(i));
          }
        }
      },
      immediate: true,
      deep: true,
    },
    tabKey(val) {
      console.log(val, "-=-=-=-==--~~~~~~~~");
      if (+val === 2) {
        let vm = this;
        this.audio = new Howl({
          src: [this.recordUrl],
          html5: true,
          onplay: function() {
            //sound playing
            vm.playing = true;

            vm.seekTimer = setInterval(() => {
              vm.seekDuration = this.seek();
            }, 1000);
          },
          onload: function() {
            vm.audioDuration = this.duration();
          },
          onpause: function() {
            clearInterval(vm.seekTimer);
            vm.playing = false;
          },
          onend: function() {
            console.log("end");
            vm.playing = false;
            vm.playCurrentNum += 1;
            // 暂时排查不出问题，end 时候先手动set 为 100%
            vm.seekDuration = 0;
            clearInterval(vm.seekTimer);
          },
          onstop: function() {
            vm.playing = false;
            vm.playCurrentNum += 1;
            // 暂时排查不出问题，end 时候先手动set 为 100%
            vm.seekDuration = 0;
            clearInterval(vm.seekTimer);
          },
        });
      } else {
        if (this.audio) {
          this.audio.stop();
        }
        if (this.htmlAudio) {
          this.htmlAudio.pause();
        }
      }
    },
  },
  methods: {
    ...mapMutations(["setSentenceCurrent", "setSentenceList"]),
    sceneClick(type) {
      if (type === "title") {
        this.titleHidden = !this.titleHidden;
        this.audio.pause();
        this.htmlAudio.src = this.data.voice;
        this.htmlAudio.play();
      }
      // play()
    },
    playHandle() {
      this.htmlAudio.pause();
      this.playing ? this.audio.pause() : this.audio.play();
      this.playing = !this.playing;
    },
    studyAgain() {
      this.$emit("recordAgain");
    },
    passByHand() {
      grammarSenRatioSub({
        chapter_id: this.reverseStatus.chapters_id,
        curr_id: this.reverseStatus.curr_id,
        sen_id: this.sentenceCurrent.id,
        score: 100,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          // 修改 pass 值 同步状态
          let currentIndex = this.sentenceList.list.findIndex(
            (v) => v.id === this.sentenceCurrent.id
          );
          this.score = 100;
          this.passByHandSuccess = true;
          this.sentenceList.list[currentIndex].pass = res.data.pass;
          this.nextList.test = res.data.test;
          this.$nextTick(() => {
            this.setSentenceList(this.sentenceList);
          });
        }
      });
    },
    studyNext() {
      if (this.nextList.test.length) {
        this.$router.push({
          path: "/reverse/group-test",
        });
      } else {
        let current = findNextTarget(
          this.sentenceList.list,
          this.sentenceCurrent.id,
          "pass",
          0
        );
        console.log(current, "----");
        if (current && current.id >= 0) {
          this.setSentenceCurrent({ id: current.id });
          this.$router.push({
            path: "/reverse/scene-into",
          });
        } else {
          this.$router.push({
            path: "/reverse/grammar-sentence",
            query: { no_next: true },
          });
        }
      }
    },
  },
  created() {},
  beforeDestroy() {
    this.audio.pause();
    if (this.htmlAudio) {
      this.htmlAudio.pause();
    }
  },
  mounted() {
    this.htmlAudio = document.getElementById("reverse-audio");
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  destroyed() {},
  activated() {},
};
</script>
<style lang="less" scope>
/* @import url(); 引入公共css类 */
@import url("./finish.less");
</style>
